const XLSX = require('xlsx')

class ExecUtils {
  constructor (filePath) {
    this.filePath = filePath
    this.workbook = XLSX.readFile(filePath)
  }

  getWorkBook () {
    return this.workbook
  }

  getSheetByName (sheetName = 'Sheet1') {
    return this.workbook.Sheets[sheetName]
  }

  /**
   * 获取最后一行 序号
   * @param { Sheet } sheet
   */
  getLastRowCount = ( sheet ) => {
    if (!sheet) {
      return new Error('表格不存在')
    }
    const rows_name = Object.keys(sheet)
    for(let idx = rows_name.length - 1; idx > 0; idx--) {
      if(/\d$/.test(rows_name[idx])) {
        return rows_name[idx].split(/(\d*)$/)[1]
      }
    }

    return 0
  }

  /**
   * 获取最后一行数据
   * @param { String } sheetName 表格名称
   * @returns
   */
  getLastRowsDataInSheet(sheet, tableRule) {
    if (!sheet) {
      return new Error('表格不存在')
    }
    const lastRowNum = this.getLastRowCount(sheet)
    const data = tableRule.map(item => {
      return item.rule(sheet[item.count + lastRowNum]?.h)
    })

    return data
  }

  writeContext() {

  }
}

module.exports = ExecUtils